package com.ydt.dockingclients.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ydt.dockingclients.api.YdtSdkApi;
import com.ydt.dockingclients.config.SdkYdtConfig;
import com.ydt.dockingclients.request.CommonJsonDataRequest;
import com.ydt.dockingclients.response.CommonDataResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.time.Instant;

@Slf4j
@Component
public class YdtClient {

    /**
     * 获取Token
     */
    public static String authToken() throws Exception {
        CommonDataResponse response = openApi(YdtSdkApi.V1_AUTH_TOKEN, null, null, CommonDataResponse.class);
        if(response.getCode()== HttpStatus.HTTP_OK){
            return com.alibaba.fastjson2.JSON.parseObject(response.getData().toString()).getString("token");
        }
        log.info("获取Token失败:{}",response);
        return null;
    }
    /**
     * 公共请求
     *
     * @param api           api信息
     * @param plaintextData 明文
     * @param token         授权
     * @return
     * @throws Exception
     */
    public static  <T> T openApi(YdtSdkApi api, String plaintextData, String token, Type type) throws Exception {

       log.info("ydtSDK={}-{}",api,plaintextData);

        String appId = SdkYdtConfig.appId;
        String appSecret = SdkYdtConfig.appSecret;

        if(StringUtils.isBlank(plaintextData)){
            plaintextData = "{'AppAPiVersion':'v1.8.0'}";
        }

        long timestamp = Instant.now().getEpochSecond();
        String data = AesCBCEncryption.encrypt(plaintextData, appSecret);
        String sign = SignUtils.makeSign(appId, appSecret, data, timestamp);

        CommonJsonDataRequest request = new CommonJsonDataRequest();
        request.setAppKey(SdkYdtConfig.appId);
        request.setData(data);
        request.setTimestamp(String.valueOf(timestamp));
        request.setSign(sign);


        log.info("请求地址：{}", api.getUrl());
        log.info("请求参数：{}", request);
        HttpRequest httpClient = HttpUtil.createPost(api.getUrl());
        httpClient.header("Content-Type", "application/json");
        if(StringUtils.isNotBlank(token)){
            log.info("token={}",token);
            httpClient.header("Authorization", token);
        }
        httpClient.body(JSON.toJSONString(request));
        HttpResponse response = httpClient.execute();

        log.info("{}-请求响应：{}", api, response.body());

        return JSON.parseObject(response.body(), type);

    }
}
